using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ServiceProviderAdd : BasePage
{
    AdminServices.ServiceProvider serviceProvider;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            lblResult.Visible = false; 
            
            LoadControls();
            
            if (Request["SPID"] != null)
            {
                AdminServices.AdminServices proxy = new AdminServices.AdminServices(); 
                
                AdminServices.ServiceProviderSearchRequest sRequest = new AdminServices.ServiceProviderSearchRequest();
                sRequest.DisplayName = Request["SPID"].ToString();
                sRequest.InPool = true;

                AdminServices.ServiceProvider[] sp = (proxy.ServiceProviderSearch(CurrentPrincipal, sRequest));
                serviceProvider = sp[0];
                if (proxy.ServiceProviderLock(CurrentPrincipal, serviceProvider.ServiceProviderID) == null)
                {                    
                    throw new Exception("Could not lock Service Provider");
                }
                BindServiceProvider();
            }
            else
            {
                serviceProvider = new AdminServices.ServiceProvider();
                serviceProvider.ServiceProviderType = new AdminServices.ServiceProviderType();
                serviceProvider.Contact = new AdminServices.Contact();
            }

            Session.Add("serviceProvider", serviceProvider);

        }

    }


    private void BindServiceProvider()
    {
        txtName.Text = serviceProvider.DisplayName;
        txtSPT.Text = serviceProvider.ServiceProviderType.ServiceProviderTypeCode;
        txtSystemName.Text = serviceProvider.SystemName;
        txtPublicKey.Text = serviceProvider.PublicKey;
        txtWebServiceURL.Text = serviceProvider.WebServiceURL;
        txtContactName.Text = serviceProvider.Contact.Name;
        txtContactAdd1.Text = serviceProvider.Contact.AddressLine1;
        txtContactAdd2.Text = serviceProvider.Contact.AddressLine2;
        txtContactCity.Text = serviceProvider.Contact.City;
        txtContactProvince.Text = serviceProvider.Contact.Province;
        txtContactPostcode.Text = serviceProvider.Contact.PostalCode;
        txtContactCountry.Text = serviceProvider.Contact.Country;
        txtContactPhone.Text = serviceProvider.Contact.Phone;
        txtContactFax.Text = serviceProvider.Contact.Fax;
        txtContactEmail.Text = serviceProvider.Contact.Email;
        ddlEncryption.SelectedIndex = ddlEncryption.Items.IndexOf(ddlEncryption.Items.FindByValue(serviceProvider.EncryptionAlgorithm));
    }

    private void LoadServiceProvider()
     {
        AdminServices.AdminServices proxy = new AdminServices.AdminServices();
        
        serviceProvider = (AdminServices.ServiceProvider)Session["serviceProvider"];


        AdminServices.ServiceProviderTypeSearchRequest sRequest = new AdminServices.ServiceProviderTypeSearchRequest();
        sRequest.DisplayName = txtSPT.Text;
        sRequest.InPool = true;
        AdminServices.ServiceProviderType[] oSPT = proxy.ServiceProviderTypeSearch(CurrentPrincipal, sRequest);
        if (oSPT.Length > 0)
        {
            serviceProvider.ServiceProviderType = oSPT[0];
        }
        else
        {
            throw new Exception("Service Provider Type does not exist");
        }

        serviceProvider.DisplayName = txtName.Text;
        serviceProvider.SystemName = txtSystemName.Text;
        serviceProvider.PublicKey = txtPublicKey.Text;
        serviceProvider.WebServiceURL = txtWebServiceURL.Text;
        serviceProvider.EncryptionAlgorithm = ddlEncryption.Text;
        serviceProvider.Contact.Name = txtContactName.Text;
        serviceProvider.Contact.AddressLine1 = txtContactAdd1.Text;
        serviceProvider.Contact.AddressLine2 = txtContactAdd2.Text;
        serviceProvider.Contact.City = txtContactCity.Text;
        serviceProvider.Contact.Province = txtContactProvince.Text;
        serviceProvider.Contact.PostalCode = txtContactPostcode.Text;
        serviceProvider.Contact.Country = txtContactCountry.Text;
        serviceProvider.Contact.Phone = txtContactPhone.Text;
        serviceProvider.Contact.Fax = txtContactFax.Text;
        serviceProvider.Contact.Email = txtContactEmail.Text;
    }


    private string SaveServiceProvider()
    {
        AdminServices.AdminServices proxy = new AdminServices.AdminServices();
        serviceProvider = (AdminServices.ServiceProvider)Session["serviceProvider"];

        try
        {
            //if (serviceProvider.ServiceProviderID != null) //if not a new service provider
            //{
            //    if (proxy.ServiceProviderLock(CurrentPrincipal, serviceProvider.ServiceProviderID) == null)
            //        throw new Exception("Could not lock Service Provider");
            //}

            LoadServiceProvider();
            serviceProvider.PublicKey = serviceProvider.PublicKey.Replace("<", "&lt").Replace(">", "&gt");

            if (!ValidateUrl(serviceProvider.WebServiceURL))
                throw new Exception("Service Provider name already exists");
            if (serviceProvider.ServiceProviderID == null)
            {
                string result;
                result = proxy.ServiceProviderInsert(CurrentPrincipal, serviceProvider);
                if (result == null)
                    throw new Exception("Service Provider name already exists");
                else if (Utilities.isInteger(result))
                {
                    serviceProvider.ServiceProviderID = result;
                    Session.Add("serviceProvider", serviceProvider);
                }
                else
                    throw new Exception(result);
            }
            else
            {
                if (!proxy.ServiceProviderUpdate(CurrentPrincipal, serviceProvider))
                    throw new Exception("Could not update Service Provider");
            }


            proxy.ServiceProviderUnlock(CurrentPrincipal, serviceProvider.ServiceProviderID);
            
            return "";
        }
        catch (Exception e)
        {
            proxy.ServiceProviderUnlockAll(CurrentPrincipal);    
            return e.Message;
        }
    }

    private bool ValidateUrl(string url)
    {
        System.Text.RegularExpressions.Regex RgxUrl = new System.Text.RegularExpressions.Regex(@"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*");

        return (RgxUrl.IsMatch(url));
    }


    protected void btnCancel_Click(object sender, EventArgs e)
    {
        lblResult.Visible = false; 
        Response.Redirect("default.aspx"); 
    }

    private void LoadControls()
    {
        // - JT hardcoded as this is apparently very unlikely to change
        // - WS changed to reflect the values used by System Adapter Base
        ddlEncryption.Items.Add("None");
        ddlEncryption.Items.Add("DES");
        ddlEncryption.Items.Add("RC2");
        ddlEncryption.Items.Add("Rijndael");
        ddlEncryption.Items.Add("TripleDES");

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        lblResult.Visible = true;
        string saveResult = SaveServiceProvider();

        if (saveResult == "")
        {
            Response.Redirect("ServiceProviderEdt.aspx");
        }
        else
        {
            lblResult.Text = saveResult;
        }
    }
}
